package com.lvyq.myplayer.ui.activity

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import coil.load
import com.google.android.material.imageview.ShapeableImageView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.current.CurrentPlayLstAdapter
import com.lvyq.myplayer.base.BaseActivity
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.common.util.DataOperationUtils
import com.lvyq.myplayer.common.util.ImgAnimatorUtils
import com.lvyq.myplayer.database.PlayerDatabase
import com.lvyq.myplayer.model.collect.PlayCollectEntity
import com.lvyq.myplayer.model.collect.PlayCollectViewModel
import com.lvyq.myplayer.model.collect.PlayCollectViewModelFactory
import com.lvyq.myplayer.model.common.EventPlayerViewModel
import com.lvyq.myplayer.parcelable.EventPopModeChange
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.service.AudioService
import com.lvyq.myplayer.util.DateUtil
import com.lvyq.myplayer.util.LrcUtil
import com.lvyq.myplayer.widget.LrcView
import com.lvyq.myplayer.widget.audio.AudioListPopWindow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**
 * 文件描述：AudioPlayerActivity
 * 作者：lvyq
 * 创建时间：2025-03-05
 * 修改时间：2025-03-05
 */
class AudioPlayerActivity : BaseActivity() ,View.OnClickListener, SeekBar.OnSeekBarChangeListener{

    lateinit var play_music_btn:ImageView
    lateinit var back_music_btn:ImageView
    lateinit var mode_music_btn:ImageView
    lateinit var pre_music_btn:ImageView
    lateinit var next_music_btn:ImageView
    lateinit var list_music_btn:ImageView
    lateinit var progressTime:TextView
    lateinit var progressTotalTime:TextView
    lateinit var  lrcView:LrcView
    lateinit var  recordCard:ShapeableImageView
    lateinit var palyBG:ImageView
    lateinit var isCollectView:ImageView
    lateinit var  needle :ImageView
    var totolDuration = 0
    var currentProgress:Int=0


    override var currentPlayAdapter:CurrentPlayLstAdapter?=null


    var songInfoData:SongInfoData? =null

    var utils: ImgAnimatorUtils? = null


    private val playCollectViewModel: PlayCollectViewModel by viewModels {
        PlayCollectViewModelFactory(PlayerDatabase.getDatabase(this).playCollectDao())
    }


    private lateinit var playerStateViewModel: EventPlayerViewModel
    //定义进度消息
    val MSG_PROGRESS = 0
    val handler = Handler(Looper.getMainLooper()) { msg ->
        when (msg.what) {
            MSG_PROGRESS -> startUpdateProgress()
        }
        true
    }

    override fun getLayoutId(): Int {
        return  R.layout.activity_aduio
    }


    /**
     * 初始化背景图
     */
    private fun initBackGroundImg(data: SongInfoData?) {
        // 内部緩存
        var downloadPicCacheDir = File(cacheDir.absolutePath + "/pic")
        val picFileName = data?.id.toString()+".png"
        val picFile = File(downloadPicCacheDir, picFileName)
        // 检查文件是否已存在
        if (picFile.exists()) {
            //设置歌曲对应的背景
            palyBG.load(picFile.path)
            //胶片
            recordCard.load(picFile.path)
            // 启动动画（60秒周期）
            utils?.startInfiniteRotation()
        }else{
            palyBG.load(data?.bgImg)
            //胶片
            recordCard.load(data?.bgImg)
            // 启动动画（60秒周期）
            utils?.startInfiniteRotation()
        }
    }


    /**
     * pop列表页点击播放模式
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun  onPopModeChangeThread (popChangMode:EventPopModeChange){
        if (popChangMode.modeChange){
            updatePlayModeBtn()
        }
    }


    /**
     * 更新播放进度
     */
    private fun startUpdateProgress() {
        //获取当前进度
        currentProgress= iService?.getProgress()?:0
        //更新进度数据-视图
        updateProgressBar(currentProgress)
        //获取到值时更新，起到平滑偏移歌词的作用
        handler.sendEmptyMessage(MSG_PROGRESS)

    }

    /**
     * 更新进度数据
     */
    private fun updateProgressBar(currentProgress: Int) {
        //更新进度数据值
        progressTime.setText(DateUtil.mill_To_mm_ss(currentProgress))
        progressTotalTime.setText(DateUtil.mill_To_mm_ss(totolDuration))
        //更新进度条
        var progressBar  =findViewById<SeekBar>(R.id.progress_sk)
        progressBar.setProgress(currentProgress)
        //更新歌词进度
        lrcView.updateProcess(currentProgress)
    }

    override fun initData() {
        //初始化播放列表，初始化adapter 。初始化Service的list
        currentPlayAdapter=getAdapter()
        initAudioPlayLst(this)

        //播放状态监听更新 1.播放暂停按钮  2播放列表中的播放状态
        initPlayStateChangeUI()

        needle = findViewById<ImageView>(R.id.recordNeedle)
        //动态背景
        progressTime=  findViewById<TextView>(R.id.progressTime)
        progressTotalTime=  findViewById<TextView>(R.id.totalTime)
        lrcView = findViewById<LrcView>(R.id.lrcView)

        palyBG= findViewById<ImageView>(R.id.play_background)
        recordCard= findViewById<ShapeableImageView>(R.id.recordCard)

        utils=ImgAnimatorUtils(recordCard)


        //初始进入设置歌曲歌词
       // lrcView.setLrcContent(LrcUtil.lrcParse(data?.lrc ?: ""))

        var from = intent.getIntExtra("from", -1)
        var position = intent.getIntExtra("position", 0)
        var currentSongData: SongInfoData? = intent.getParcelableExtra("data")

        //注册EventBus
        EventBus.getDefault().register(this)
        //通过audioservice 播放,混合启动，保证退出当前页仍然播放
        val audioIntent = Intent(this, AudioService::class.java)
        //传递值到AudioService中
        audioIntent.putExtra("data",currentSongData)
        audioIntent.putExtra("from",from)
        audioIntent.putExtra("position",position)

        //intent.putParcelableArrayListExtra("songLst",songLst)
        //绑定 BIND_AUTO_CREATE 服务未创建时创建并绑定
        bindService(audioIntent,connection, BIND_AUTO_CREATE)
        //启动
        startService(audioIntent)


    }


    /**
     * 播放监听，播放状态UI、播放中图标
     */
    private fun initPlayStateChangeUI() {
        // 初始化 ViewModel
        playerStateViewModel = ViewModelProvider(this)[EventPlayerViewModel::class.java]
        // 观察状态变化
        playerStateViewModel.eventPlayState.observe(this) { eventState ->
            // 在这里处理状态变化
            if (eventState.playState){
                //播放中 ，将按钮更为暂停
                play_music_btn.setImageResource(R.mipmap.audio_stop)

            }else{
                play_music_btn.setImageResource(R.mipmap.aduio_bofang)
            }
        }
        //播放图标更新
        playerStateViewModel.eventCurSongId.observe(this){eventCurrentSongId->
            currentPlayAdapter?.let {
                it.refreshPlayPosition(eventCurrentSongId.ponsiton)
            }
        }

        //切换歌曲 .虽然不如EventBus逻辑直观。但好在可以很好的监听歌曲切换
        playerStateViewModel.eventPlaySong.observe(this){data->
            //歌名
            Log.i("AudioPlayerActivity","歌曲切换:"+data.title.toString())
            var title = findViewById<TextView>(R.id.title)
            var singer = findViewById<TextView>(R.id.singer)
            data?.let {
                title.setText(data.title)
                singer.setText(data.singer)
            }

            //按钮初始化更新
            updatePlayStateBtn(true)
            //获取总进度
            totolDuration= iService?.getTotalDuration()?:0
            //传值到lrcView
            lrcView.setSongDuration(totolDuration)
            //初始从进入设置歌曲歌词
            lrcView.setLrcContent(LrcUtil.lrcParse(data?.lrc ?: ""))
            //设置最大进度
            var progressBar  =findViewById<SeekBar>(R.id.progress_sk)
            progressBar.max=totolDuration
            //更新播放进度
            startUpdateProgress()
            //更新播放模式UI
            updatePlayModeBtn()
            //判断是否收藏
            lifecycleScope.launch {
                var collect= playCollectViewModel.getPlayCollectByBusinessKeyAndType(data?.id ?: -1, 1)
                if (collect!=null){
                    updateCollectUI(1)
                }else{
                    //更新收藏狀態
                    updateCollectUI(0)
                }
            }

            //初始化背景图
            initBackGroundImg(data)
            songInfoData=data

        }
    }





    /**
     * 监听
     */
    override fun initListener() {
        play_music_btn =findViewById<ImageView>(R.id.play_music)
        play_music_btn.setOnClickListener(this)

        //返回按钮 关闭当前页
        back_music_btn=findViewById<ImageView>(R.id.back)
        back_music_btn.setOnClickListener{ finish() }

        //进度条监听
        var progressBar  =findViewById<SeekBar>(R.id.progress_sk)
        progressBar.setOnSeekBarChangeListener(this)

        //模式切换监听
       mode_music_btn=  findViewById<ImageView>(R.id.mode_music)
        mode_music_btn.setOnClickListener(this)

        //上一曲，下一曲监听
        pre_music_btn =findViewById(R.id.pre_music)
        pre_music_btn.setOnClickListener(this)

        next_music_btn =findViewById(R.id.next_music)
        next_music_btn.setOnClickListener(this)

        //列表监听
        list_music_btn=findViewById<ImageView>(R.id.list_music)
        list_music_btn.setOnClickListener(this)

        var lrcView2 = findViewById<LrcView>(R.id.lrcView)
        //歌词拖动进度监听
        lrcView2.setProgressListener {
            //更新播放进度
            iService?.seekTo(it)
            updateProgressBar(it)
        }

        //收藏监听
        isCollectView= findViewById<ImageView>(R.id.isCollect)
        isCollectView.setOnClickListener(this)

    }





    //使用  View.OnClickListener 全局监听点击事件
    override fun onClick(v: View?) {
        when(v?.id){
            R.id.play_music->updatePlayStateBtn(false)
            R.id.mode_music->updateModeStateBtn()
            R.id.pre_music->iService?.preMusicPlay()
            R.id.next_music->iService?.nextMusicPlay()
            R.id.list_music->showPlayLst()
            R.id.isCollect->collectAudio()
        }
    }

    /**
     * 收藏
     */
    private fun collectAudio() {
        songInfoData?.let {
            lifecycleScope.launch {
                var entity =
                    playCollectViewModel.getPlayCollectByBusinessKeyAndType(it.id , 1)
                if (entity!=null){
                    myToast("取消收藏")
                    playCollectViewModel.deleteByBusinessKey(it.id, 1)
                    updateCollectUI(0)
                } else{
                    //添加收藏
                    songInfoData?.let {
                        it.isCollect=1
                        val currentTimeStamp = System.currentTimeMillis()
                        val newEntry = PlayCollectEntity(title=it.title?:"",
                            businessKey = it.id,
                            singer = it.singer,
                            bgImg = it.bgImg?:"",
                            url = it.song,
                            lrc = it.lrc,
                            singerId = it.singerId,
                            publishDate = it.publishDate,
                            albumId = it.albumId,
                            albumName = it.albumName,
                            createTime = currentTimeStamp,
                            updateTime = currentTimeStamp,
                            totalDuration = 0,
                            playCount = 1,
                            type = 1)

                        playCollectViewModel.insertPlayCollect(newEntry)
                        myToast("收藏成功")
                        updateCollectUI(1)
                    }
                }
        }

        }
        }


    private fun updateCollectUI(collect: Int?) {
        if (collect==1){
            isCollectView.setImageResource(R.mipmap.audio_collect)
        }else{
            isCollectView.setImageResource(R.mipmap.audio_collect_un)
        }
    }

    private fun getAdapter():CurrentPlayLstAdapter {
        return CurrentPlayLstAdapter(this)
    }

    /**
     * 显示歌单列表
     */
     fun showPlayLst() {
        var bottom=  findViewById<LinearLayout>(R.id.audio_play_bottom)
        var height = bottom.height

        var playLstWindow = AudioListPopWindow(this@AudioPlayerActivity,currentPlayAdapter,iService)
        if (!playLstWindow.isShowing){
            playLstWindow.showAsDropDown(bottom,0, -height*2)
        }

    }

    /**
     * 更新自定播放模式
     */
    private fun updateModeStateBtn() {
        //设置播放模式
        iService?.setPlayMode()
        //更新模式ui
        updatePlayModeBtn()
    }

    /**
     * 更新播放模式按钮
     */
    private fun updatePlayModeBtn() {
        //获取当前播放模式
        var playMode = iService?.getPlayMode()
        //根据模式设置样式
        when(playMode){
            AudioService.PLAY_MODE_ALL ->{
                mode_music_btn.setImageResource(R.mipmap.audio_mode_all)
            }
            AudioService.PLAY_MODE_SINGLE ->{
                mode_music_btn.setImageResource(R.mipmap.audio_mode_single)
            }
            AudioService.PLAY_MODE_RANDOM ->{
                mode_music_btn.setImageResource(R.mipmap.audio_mode_random)
            }

        }
    }

    /**
     * 更新播放暂停按钮
     */
    private fun updatePlayStateBtn( isPlayStart:Boolean) {
       var playState = iService?.updPlayState(isPlayStart)
        playState?.let {
            //更新ui
            if (playState) {
                //播放中 ，将按钮更为暂停
                play_music_btn.setImageResource(R.mipmap.audio_stop)
                //停止旋转
                utils?.toggleRotation(true)
                //唱片唱针处理
                resetNeedleAnimation(needle)
                //开启更新进度
                handler.sendEmptyMessageDelayed(MSG_PROGRESS,100)
            } else {
                //暂停，将按钮更为播放中
                play_music_btn.setImageResource(R.mipmap.aduio_bofang)
                //旋转
                utils?.toggleRotation(false)
                startNeedleAnimation(needle)

                //停止更新进度进程
                handler.removeMessages(MSG_PROGRESS)

            }
        }
    }





    override fun onDestroy() {
        super.onDestroy()
        //解绑Servie
        unbindService(connection)
        //反注册EventBus -不进行反注册，全局执行-退出播放页后自动播放无法正常收到通知
        EventBus.getDefault().unregister(this)
        //情空handler所以消息，防止内存泄露
        handler.removeCallbacksAndMessages(null)
        //停止并释放资源
        utils?.stopAnimation()
    }

    /**
     * 进度改变回调
     * fromUser true  用户拖动  false通过代码改变进度
     */
    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        //判断是否是用户操作
        if (!fromUser) return
        //更新播放进度
        iService?.seekTo(progress)
        //更新界面显示
        //更新播放进度
       startUpdateProgress()

        // updateProgressBar(progress)
    }

    /**
     * 手指触摸回调
     */

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    /**
     * 手指离开回调
     */
    override fun onStopTrackingTouch(seekBar: SeekBar?) {
    }

}